package com.mck.service.impl;

import com.mck.entity.Subject;
import com.mck.mapper.SubjectMapper;
import com.mck.service.SubjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author Max
 * @Date 2025/3/10 下午5:32
 */
@Service
public class SubjectServiceImpl implements SubjectService {

    @Autowired
    private SubjectMapper subjectMapper;

    // 获取全部科目（缓存整个列表）
    @Override
    @Cacheable(value = "subjectList", key = "'all'", unless = "#result.isEmpty()")
    public List<Subject> getSubjectList() {
        return subjectMapper.getSubjectList();
    }

    // 获取单个科目（已缓存）
    @Override
    @Cacheable(value = "subject", key = "#id", unless = "#result == null")
    public Subject getSubjectById(Integer id) {
        return subjectMapper.selectById(id);
    }

    // 批量获取科目（复用单个缓存）
    @Override
    public List<Subject> getSubjectsByIds(List<Integer> subjectIds) {
        return subjectIds.stream().map(this::getSubjectById).filter(Objects::nonNull).collect(Collectors.toList());
    }

    // 添加科目
    @Override
    @CacheEvict(value = "subjectList", key = "'all'")
    public void addSubject(Subject subject) {
        subjectMapper.addSubject(subject);
    }

    // 删除科目
    @Override
    @CacheEvict(value = "subjectList", key = "'all'")
    public void deleteSubject(Integer id) {
        subjectMapper.deleteSubject(id);
    }
}
